package com.yds.baseproject_java;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import com.identity.Files;
import com.identity.Shell;
import com.identity.Util;
import com.identity.globalEnum;

import android.content.Context;


public class TestJarActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    private ImageView iv;
    private Button btnInit;
    private Button btnExit;
    private Button btnGetData;
    private Button btnRegist;
    private ListView lvInfoView;
    private BluetoothAdapter mAdapter;
    private BluetoothDevice mDevice = null;
    private ArrayAdapter<String> mInfoView;
    private static final int REQUEST_ENABLE_BT = 2;
    private Shell shell = null;
    private boolean bInitial = false;
    private boolean bStop = false;
    private boolean bConnected = false;
    private Context context;

    private String packageName;

    public boolean OnKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            bStop = true;
            finish();
        }
        return false;
    }

    private class ButtonExitOnClick implements OnClickListener {
        public void onClick(View v) {
            bStop = true;
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bStop = true;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            if (mDevice != null) {
                Log.w("ComShell", "mDevice is not null");
                if (shell != null) {
                    Log.w("ComShell", "shell is not null");
                    shell.Destroy();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        iv = (ImageView) findViewById(R.id.ivImageview);
        mInfoView = new ArrayAdapter<String>(this, R.layout.tv_infoview);
        lvInfoView = (ListView) findViewById(R.id.lvInfoview);
        lvInfoView.setAdapter(mInfoView);
        lvInfoView.setVisibility(View.VISIBLE);
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        btnInit = (Button) findViewById(R.id.btnInit);
        btnExit = (Button) findViewById(R.id.btnExit);
        btnInit.setOnClickListener(new ButtonInitOnClick());
        btnExit.setOnClickListener(new ButtonExitOnClick());
//		Files file = new Files(this.getApplicationContext());
//		copyLibFile();
        packageName = this.getPackageName();
        if (mAdapter == null) {
            mInfoView.add("mAdapter is null!");
        }
        if (!mAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String str;
                str = device.getName().substring(0, 3);
                Log.w("YDSimon", "device.getName().substring(0, 1) is:" + str);
                if ((str.equalsIgnoreCase("SYN")) || (str.equalsIgnoreCase("SS-")) || (str.equalsIgnoreCase("PSB"))) {
                    mDevice = device;
                    Log.w("YDSimon", "device.getName() is SYNTHESIS" + device.getAddress() + "  " + device.getName());
                } else {
                    Log.w("YDSimon", "device.getName() is not SYNTHESIS");
                    boolean bAllNum = false;
                    if (device.getName().length() > 9) {
                        str = device.getName().substring(0, 10);
                        bAllNum = str.matches("[0-9]+");
                        Log.w("YDSimon", "bAllNum " + bAllNum);
                        if (bAllNum == true) {
                            mDevice = device;
                        }
                    }
                }
                mInfoView.add(device.getName() + "====" + device.getAddress());
            }
            try {
                mAdapter.cancelDiscovery();
                context = this.getApplicationContext();
                if (mDevice != null)
                    shell = new Shell(context, mDevice);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.w("YDSimon", "Socket connect error！");
                mInfoView.add("与机具建立连接失败，请尝试重新启动应用程序!");
            }
            Log.w("YDSimon", "Socket connect OK！");
        }
    }

    private class ButtonInitOnClick implements OnClickListener {
        public void onClick(View v) {
            globalEnum ge = globalEnum.NONE;
            Log.w("YDSimon", "In ButtonInitOnClick shell 00 " + shell);
            //mInfoView.add("ButtonInitOnClick");
            if (shell == null) {
                Log.w("YDSimon", "In ButtonInitOnClick shell is null");
                try {
                    if (mDevice == null) {
                        mInfoView.add("与机具建立连接失败，请检查蓝牙配置");
                        Log.w("YDSimon", "与机具建立连接失败，请检查蓝牙配置");
                        return;
                    }
                    shell = new Shell(context, mDevice);
                    Log.w("YDSimon", "In ButtonInitOnClick shell " + shell);
                } catch (Exception e) {
                    Log.w("YDSimon", "In ButtonInitOnClick shell Exception" + e.getMessage());
                    e.printStackTrace();
                }
            }

            try {
                Log.w("YDSimon", "shell.Register() = " + shell.Register());
                if (shell.Register()) {
                    //0316 btnRegist.setEnabled(false);
                    mInfoView.add("取机具编号成功！");
                    ge = shell.Init();
                    if (ge == globalEnum.INITIAL_SUCCESS) {
                        bInitial = true;
                        btnInit.setEnabled(false);
                        mInfoView.add("建立连接成功！");
                        bConnected = true;
                        new Thread(new GetDataThread()).start();
                    } else {
                        shell.EndCommunication();//0316
                        mInfoView.add("与机具建立连接失败，请检查蓝牙配置8");
                    }
                } else {
                    mInfoView.add("与机具建立连接失败，请检查蓝牙配置9");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.w("YDSimon", "Exception = " + e.getMessage());
            }
        }
    }

    class ButtonRegistOnClick implements OnClickListener {

        public void onClick(View v) {
            try {
                if (shell.Register()) {
                    mInfoView.add("取机具编号成功！");
                } else {
                    mInfoView.add("没搜索到蓝牙设备，请重新执行应用程序！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private class ButtonGetDataOnClick implements OnClickListener {
        public void onClick(View v) {
            btnGetData.setEnabled(false);
            new Thread(new GetDataThread()).start();
        }
    }

    //0316
    private class GetDataThread implements Runnable {
        private String data;
        private byte[] cardInfo = new byte[256];
        private int count = 0;
        private Message msg;//主要改了这个地方，好像启作用了
        private String wltPath = "";
        private String termBPath = "";
        private boolean bRet = false;


        public GetDataThread() {
        }

        public void run() {
            globalEnum ge = globalEnum.GetIndentiyCardData_GetData_Failed;
            try {
                Thread.sleep(2000);

                globalEnum gFindCard = globalEnum.NONE;
                long start = System.currentTimeMillis();
                while (!bStop) {
                    data = null;//
                    msg = handler.obtainMessage(71, data);//发送消息
                    handler.sendMessage(msg);
                    bRet = shell.SearchCard();
                    if (bRet) {
                        data = null;//
                        msg = handler.obtainMessage(1, data);//发送消息
                        handler.sendMessage(msg);
                        bRet = shell.SelectCard();
                        if (bRet) {
                            data = null;//
                            msg = handler.obtainMessage(2, data);//发送消息
                            handler.sendMessage(msg);
                            //Thread.sleep(100);

                            int nRet = shell.ReadCardWithFinger();//nRet 1:二代证无指纹 2：二代证包含指纹
                            if (nRet > 0) {
                                data = null;//
                                byte[] fingerBuff = new byte[1024];
                                byte[] wltBuff = new byte[1024];
                                if (nRet == 2) {
                                    bRet = shell.GetFingerData(fingerBuff);
                                    //	Log.w("ComShell","fingerData is:"+Util.toHexStringNoSpace(fingerBuff, 1024));
                                }

                                msg = handler.obtainMessage(3, data);//发送消息
                                handler.sendMessage(msg);

                                cardInfo = shell.GetCardInfoBytes();
                                if (shell.GetCardTypeFlag(cardInfo) == 0) {//0时为二代证信息
                                    data = String.format(
                                            "姓名：%s 性别：%s 民族：%s 出生日期：%s 住址：%s 身份证号：%s 签发机关：%s 有效期：%s-%s",
                                            shell.GetName(cardInfo), shell.GetGender(cardInfo), shell.GetNational(cardInfo),
                                            shell.GetBirthday(cardInfo), shell.GetAddress(cardInfo),
                                            shell.GetIndentityCard(cardInfo), shell.GetIssued(cardInfo),
                                            shell.GetStartDate(cardInfo), shell.GetEndDate(cardInfo));
                                    if (nRet == 2) {
                                        data = data + "\r\n" + "指纹特征值已读取";
                                    } else if (nRet == 1) {
                                        data = data + "\r\n" + "不包含指纹";
                                    }
                                } else if (shell.GetCardTypeFlag(cardInfo) == 1) {//1时为外国人居住证信息
                                    data = String.format(
                                            "英文名字：%s 中文名字：%s 性别：%s 国籍代码：%s 国籍名称：%s 出生日期：%s 身份证号：%s 签发机关：%s 有效期：%s-%s　关联项：%s 换证次数：%s 证件类型：%s",
                                            shell.GetFEName(cardInfo), shell.GetFCName(cardInfo), shell.GetFGender(cardInfo), shell.GetFCountryCode(cardInfo), shell.GetFCountryName(cardInfo),
                                            shell.GetFBirthday(cardInfo),
                                            shell.GetFIndentityCard(cardInfo), shell.GetFIssued(cardInfo),
                                            shell.GetFStartDate(cardInfo), shell.GetFEndDate(cardInfo), shell.GetFRelatedItem(cardInfo), shell.GetFVersion(cardInfo), shell.GetFTypeFlag(cardInfo));
                                    if (nRet == 2) {
                                        data = data + "\r\n" + "指纹特征值已读取";
                                    } else if (nRet == 1) {
                                        data = data + "\r\n" + "不包含指纹";
                                    }
                                } else if (shell.GetCardTypeFlag(cardInfo) == 2)//2为港澳台居住证信息
                                {
                                    data = String.format(
                                            "姓名：%s 性别：%s 出生日期：%s 住址：%s 身份证号：%s 签发机关：%s 有效期：%s-%s 通行证号码：%s 签发次数：%s 证件类型：%s",
                                            shell.GetGName(cardInfo), shell.GetGGender(cardInfo), shell.GetGBirthday(cardInfo),
                                            shell.GetGAddress(cardInfo), shell.GetGIndentityCard(cardInfo),
                                            shell.GetGIssued(cardInfo), shell.GetGStartDate(cardInfo),
                                            shell.GetGEndDate(cardInfo), shell.GetGPassNum(cardInfo),
                                            shell.GetGSignNum(cardInfo), shell.GetGTypeFlag(cardInfo));
                                    if (nRet == 2) {
                                        data = data + "\r\n" + "指纹特征值已读取";
                                    } else if (nRet == 1) {
                                        data = data + "\r\n" + "不包含指纹";
                                    }
                                } else {
                                    msg = handler.obtainMessage(6, data);//读卡失败
                                    handler.sendMessage(msg);    //readC
                                    break;
                                }
                                msg = handler.obtainMessage(0, data);//发送消息
                                handler.sendMessage(msg);

                                //	Log.w("777"," shell.GetEndDate(cardInfo) is:"+ shell.GetEndDate(cardInfo));
                                byte[] bmpBuff = new byte[38862];
                                boolean bRet = shell.GetWltData(wltBuff);
                                if (bRet) {
                                    Log.w("ComShell", "packageName is :" + packageName);
                                    nRet = shell.GetPicByBuff(packageName, wltBuff, bmpBuff);
                                    Log.w("ComShell", "GetPicByBuff nRet is:" + nRet);
                                    if (nRet == 1) {
                                        Bitmap bm = BitmapFactory.decodeByteArray(
                                                bmpBuff, 0, 38862);
                                        if (bm != null) {
                                            msg = handler.obtainMessage(100, bm);//发送消息
                                            handler.sendMessage(msg);
                                        }
                                    } else if (nRet == -5) {
                                        msg = handler.obtainMessage(101, data);//发送消息
                                        handler.sendMessage(msg);
                                    } else if (nRet == -1) {
                                        msg = handler.obtainMessage(102, data);//发送消息
                                        handler.sendMessage(msg);
                                    }
                                    //break;//0316  调试用，所以增加
                                }
                            } else {
                                msg = handler.obtainMessage(6, data);//发送消息
                                handler.sendMessage(msg);    //readCard error
                            }
                        } else {
                            msg = handler.obtainMessage(5, data);//发送消息
                            handler.sendMessage(msg);    //selectCard error
                        }
                    } else {
                        msg = handler.obtainMessage(4, data);//发送消息
                        handler.sendMessage(msg);    //searchCard error
                    }
                    Thread.sleep(50);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                Log.e("tag", e.getMessage());
                e.printStackTrace();
            }
        }
    }


    public Handler handler = new Handler() {//处理UI绘制
        private String data;
        private Bitmap bm;
        private int t_sec1, t_sec2;
        private int t_msec1, t_msec2;

        private Calendar t;

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {//M_ERROR  M_VALIDATE_ERROR I_ERROR I_VALIDATE_ERROR
            switch (msg.what) {                    //C_ERROR  C_VALIDATE_ERROR D_ERROR D_VALIDATE_ERROR
                case 0:
                    data = (String) msg.obj;
                    if (data == null) {
                    } else {
                        //mInfoView.clear();
                        t = Calendar.getInstance();
                        t_sec2 = t.get(Calendar.SECOND);
                        t_msec2 = t.get(Calendar.MILLISECOND);
                        int d = t_sec2 - t_sec1;
                        int md = t_msec2 - t_msec1;
                        if (d < 0)
                            d = d + 60;
                        if (md < 0) {
                            d = d - 1;
                            md = md + 1000;
                        }
                        mInfoView.add("readcard time is:  " + d + "." + md + "s");
                        mInfoView.add(data);
                    }
                    break;
                case 71:
                    t = Calendar.getInstance();
                    t_sec1 = t.get(Calendar.SECOND);
                    t_msec1 = t.get(Calendar.MILLISECOND);
                    break;
                case 100:
                    bm = (Bitmap) msg.obj;
                    iv.setImageBitmap(bm);

                    //  deleteFile("zp.bmp");

                    break;
                case 101:
                    mInfoView.add("照片解码授权文件不正确");
                    break;
                case 102:
                    mInfoView.add("照片原始数据不正确");
                    break;
                case 1:
                    mInfoView.clear();
                    iv.setImageBitmap(null);
                    //mInfoView.add("SearchCard ok");
                    break;
                case 4:
//			mInfoView.clear();
//			mInfoView.add("SearchCard error");
                    //mInfoView.add("正在寻卡...");
                    break;
                case 5:
                    mInfoView.clear();
                    mInfoView.add("SelectCard error");
                    break;
                case 6:
                    mInfoView.clear();
                    mInfoView.add("ReadCard error");
                    break;
                case 87:
                    mInfoView.clear();
                    mInfoView.add("读卡初始化中，请稍候...");
                    break;
                case 88:
                    mInfoView.clear();
                    mInfoView.add("机具信息监听中...");
                    break;
                case 99:
                    mInfoView.clear();
                    iv.setImageBitmap(null);
                    break;
                default:
                    break;
            }
        }
    };
    //0316
/*
		private void copyLibFile(){
			String path = Environment.getExternalStorageDirectory() + "/sdseslib";
			String filename1 = path + "/" + "base.dat";
			String filename2 = path + "/" + "license.lic";
			File dir = new File(path);
			if (!dir.exists()) {
			    dir.mkdir();
			}
			try {
			     if (!(new File(filename1)).exists()) {
			    	 InputStream is = null ;
			    	 is = this.getApplicationContext().getResources().openRawResource(R.raw.base);
			    	 int size = is.available();
			    	 FileOutputStream fos = new FileOutputStream(filename1);
			    	 byte[] buffer = new byte[8192];
			    	 int count = 0;
			    	 while ((count = is.read(buffer)) > 0) {
			    		 fos.write(buffer, 0, count);
			    	 }
			    	 fos.flush();
			    	 fos.close();
			    	 is.close();
			     }else{
			    	 Log.w("ComShell", "file exist:" + filename1);
			     }
			     if (!(new File(filename2)).exists()) {
			    	 InputStream is = null ;
			    	 is = this.getApplicationContext().getResources().openRawResource(R.raw.license);
			    	 int size = is.available();
			    	 FileOutputStream fos = new FileOutputStream(filename2);
			    	 byte[] buffer = new byte[8192];
			    	 int count = 0;
			    	 while ((count = is.read(buffer)) > 0) {
			    		 fos.write(buffer, 0, count);
			    	 }
			    	 fos.flush();
			    	 fos.close();
			    	 is.close();
			     }else{
			    	 Log.w("ComShell", "file exist:" + filename2);
			     }
			   	} catch (FileNotFoundException e) {
			   		Log.e("Database", "File not found");
			   		e.printStackTrace();
			   	} catch (IOException e) {
			   		Log.e("Database", "IO exception");
			   		e.printStackTrace();
			   }
		}*/

}